<template>
  <div id="purposeBxInfoDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text"
          class="button-blue"
          icon="vxe-icon-refresh"
          content="刷新"
          :loading="rloading"
          :disabled="isEmpty(purposeId)"
          @click="findPurposeAndDetailList"></vxe-button>
        <vxe-button type="text"
          class="button-blue"
          icon="vxe-icon-save"
          content="保存"
          :disabled="isEmpty(purposeId)"
          @click="saveBathPurposeDetail"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table
        ref="purposeDetailTableRef"
        class="mytable-scrollbar"
        border="inner" align="center"
        height="auto"
        :row-config="{ isCurrent: true, isHover: true }"
        :data="detailList"
        :loading="rloading"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
        resizable show-overflow
        keep-source>
        <vxe-column
          field="sampleTypeName"
          title="标本类型" width="100">
           <template #default="{ row }">
            <span>{{ row.sampleTypeName }}{{row.dataType=="purpose"?'(默认)':''}}</span>
          </template>
        </vxe-column>
        <vxe-column field="bxWorkFlowNo"
          title="方案流程" width="200"
          :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.bxWorkFlowName }}</span>
          </template>
          <template
            #edit="{ row, rowIndex, column }">
            <SelectDataGrid
              :url="'/api/bac/bac-work-flow/findBacWorkFlowList'"
              :column="[
                          { field: 'workFlowCode', title: '编码' },
                          { field: 'workFlowName', title: '名称' }
                        ]"
              :searchParam="{ isStop: 'false' }"
              :isPage="false"
              @SelectCellClick="
                          (e) => {
                            selectBxWorkFlowRow(e, rowIndex);
                          }
                        "
              :showField="'workFlowName'">
            </SelectDataGrid>
          </template>
        </vxe-column>
        <vxe-column
          field="bxCulCombinaNos"
          title="培养基组合"
          :edit-render="{}">
          <template #default="{ row }">
            <span>{{ formatCombinationNameByIds(row) }}</span>
          </template>
          <template
            #edit="{ row,rowIndex }">
            <SelectDataCheckedList
              :url="'/api/bac/bac-cultrue-combination/findBacCultureCombinationList'"
              ref="ruleSelectListRef"
              :column="[
                      { field: 'code', title: '编号' }, //列标题
                      { field: 'name', title: '名称' }
                    ]"
              :searchParam="{}"
              :isPage="false"
              @SelectCellClick="
                      (e) => {
                        selectBxCultureCombinationRow(e, rowIndex);
                      }
                    "
              :clickRowId="row.bxCultureCombinationIds">
            </SelectDataCheckedList>
          </template>
        </vxe-column>

      </vxe-table>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';

let store = AppStore();
defineExpose({ initPage });
let purposeId = null;
let purposeNo = null;
let cultureCombinationList: any = reactive([]);
let detailList: any = reactive([]);
let rloading = ref(false);

function initPage(row: any) {
  purposeId = row.id;
  purposeNo = row.purposeNo;
  findPurposeAndDetailList();
  getCultureCombinationList();
}
async function getCultureCombinationList() {
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationList';
  const data = await proxy.$http.get(url);
  cultureCombinationList.push(...data.data);
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findPurposeAndDetailList() {
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  if (isEmpty(purposeId)) {
    rloading.value = false;
    return;
  }
  const url = '/api/bac/bacReqPurposeDetail/findPurposeAndDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { purposeId: purposeId,purposeNo: purposeNo }
    })
    .then((res: any) => {
      detailList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

// 左侧保存
async function saveBathPurposeDetail() {
  if (isEmpty(purposeId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.purposeDetailTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      const sveOrupdateDetail = [] as any[];
      updateRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          purposeId: e.purposeId,
          purposeNo: e.purposeNo,
          sampleTypeId: e.sampleTypeId,
          sampleTypeCode: e.sampleTypeCode,
          bxWorkFlowNo: e.bxWorkFlowNo,
          bxCulCombinaNos: e.bxCulCombinaNos,
          bxCultureCombinationIds: e.bxCultureCombinationIds,
          dataType: e.dataType
        };

        sveOrupdateDetail.push(iDetail);
      });
      if (sveOrupdateDetail.length > 0) {
        const url = '/api/bac/bacReqPurposeDetail/updatePurposeAndDetail';
        const obj: any = {};
        obj.purposeAnddetailList = sveOrupdateDetail;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            findPurposeAndDetailList();
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}

function selectBxWorkFlowRow(row, index) {
  detailList[index].bxWorkFlowName = row.workFlowName;
  detailList[index].bxWorkFlowNo = row.workFlowCode;
}
function selectBxCultureCombinationRow(row, index) {
  const nameArr = [];
  const idArr = [];
  let nos = [];

  row.forEach((item) => {
    nameArr.push(item.name);
    idArr.push(item.id);
    nos.push(item.code);
  });
  const noString = nos.join(',');
  detailList[index].bxCultureCombinationIds = noString;
  detailList[index].bxCulCombinaNos = noString;

}

function formatCombinationNameByIds(row) {
  if (!isEmpty(row.bxCulCombinaNos)) {
    const ruleNames: any = [];
    const ruelIdList = row.bxCulCombinaNos.split(',');
    for (const ruelId of ruelIdList) {
      const item = cultureCombinationList.find((item) => item.code === ruelId);
      if (!isEmpty(item)) {
        ruleNames.push(item.name);
      }
    }
    return ruleNames.join(',');
  } else {
    return '';
  }

  // qcRuleList.filter(p=>p.isVisiable)

  // const obj = materialItemList.filter((p: any) => {
  //   defaultSelecteRowKeys.push(p.qcItemId);
  //   return p.qcItemId == row.id;
  // });
}
</script>

<style lang="scss" scoped>
#purposeBxInfoDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
